package hcb.dms.khuVuc;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import hcb.dms.CameraPhotoCapture;
import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.UserSessionManager;
import hcb.dms.khachHang.Edit_khachHang;

public class Dm_khuVuc extends Activity {

    Activity activity = null;
	private ListView lv;
	// Progress Dialog
	private ProgressDialog pDialog;
    String id_maKhu_Vuc ="";
	// Creating JSON Parser object
	JSONParser jParser = new JSONParser();

	ArrayList<HashMap<String, String>> productsList;

	// url to get all products list
    // JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_KHUVUC = "khuVuc";
	private static final String TAG_MAKV = "maKV";
	private static final String TAG_TENKV = "tenKV";
    private static final String TAG_MANV = "maNV";

	// products JSONArray
	JSONArray products = null;
	UserSessionManager session;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_khu_vuc);
        activity = this;//luu thong tin Activity
		session = new UserSessionManager(getApplicationContext());
		// Hashmap for ListView
		productsList = new ArrayList<HashMap<String, String>>();

		// Loading products in Background Thread
		new LoadAllKhuVuc().execute();

		// Get listview
		lv = (ListView) findViewById(R.id.list);
        this.registerForContextMenu(lv);// Dang ky ContextMenu in ListView
		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				// getting values from selected ListItem
				String pid = ((TextView) view.findViewById(R.id.maKV)).getText().toString();
                id_maKhu_Vuc = pid;
				// Starting new intent
                activity.openContextMenu(lv);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.dm_khu_vuc, menu);
		return true;
	}
    @Override
    public void onCreateContextMenu( ContextMenu menu, View v,ContextMenu.ContextMenuInfo  menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId()==R.id.list) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_list, menu);
        }
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.add) {
            Toast.makeText(this, "Them moi ", Toast.LENGTH_SHORT).show();
        } else if (item.getItemId() == R.id.edit) {
            Toast.makeText(this, "Sua du lieu ", Toast.LENGTH_SHORT).show();
            Intent in = new Intent(getApplicationContext(),Edit_khuVuc.class);
            // sending pid to next activity
            in.putExtra(TAG_MAKV, id_maKhu_Vuc);
            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        } else if (item.getItemId() == R.id.delete) {
            Toast.makeText(this, "Xoa du lieu", Toast.LENGTH_SHORT).show();
            //CameraPhotoCapture
            Intent i = new Intent(getApplicationContext(), CameraPhotoCapture.class);
            startActivity(i);
        } else {
            return false;
        }
        return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * Background Async Task to Load all product by making HTTP Request
	 */
	class LoadAllKhuVuc extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Dm_khuVuc.this);
			pDialog.setMessage("Loading Khu vuc. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
			System.out.println(Thread.currentThread().getName()+" ...start!");

		}

		/**
		 * getting All products from url
		 */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME,session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD,session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP,"OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "LKV"));

			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(session.URL, "POST", params);

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// products found
					// Getting Array of Products
					products = json.getJSONArray(TAG_KHUVUC);

					// looping through All Products
					for (int i = 0; i < products.length(); i++) {
						JSONObject c = products.getJSONObject(i);

						// Storing each json item in variable
						String id = c.getString(TAG_MAKV);
						String ten = c.getString(TAG_TENKV);
						String maNV = c.getString(TAG_MANV);

						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_MAKV, id);
						map.put(TAG_TENKV, ten);
						map.put(TAG_MANV,maNV);

						// adding HashList to ArrayList
						productsList.add(map);
					}
				} else {
					// no products found
					// Launch Add New product Activity
			//		Intent i = new Intent(getApplicationContext(),Edit_khuVuc.class);
					// Closing all previous activities
			//		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			//		startActivity(i);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("All khu vuc: ", json.toString());
			}

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					Log.d("All khu vuc: ","abc" );
					ListAdapter adapter = new SimpleAdapter(
							Dm_khuVuc.this, productsList,
							R.layout.item_khu_vuc, new String[]{TAG_MAKV, TAG_TENKV, TAG_MANV}, new int[]{R.id.maKV, R.id.tenKV, R.id.maNV});
					lv = (ListView) findViewById(R.id.list);
					lv.setAdapter(adapter);
				}
			});

		}

	}

}
